<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
  
  <script type="module">
    import { reactive, effect, computed, watch } from './reactivity/index.js'

    const data = {
      foo: 0,
      bar: 1,
    }

    const obj = reactive(data)

    // watch(obj, () => {
    //   console.log('update')
    // })
    // obj.foo = 1

    // watch(
    //   () => obj.foo,
    //   (newval, oldVal) => {
    //     console.log(newval, oldVal)
    //   }
    // )

    // watch(obj, (oldValue, newValue) => {
    //   console.log(oldValue, newValue)
    //   console.log('update')
    // }, {
    //   // immediate: true,
    //   flush: 'post'
    // })


    const fetch = (data) => {
      const dataMap = new Map([
        [1, '西瓜'],
        [2, '苹果'],
        [3, '香蕉'],
      ])
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(dataMap.get(data))
        }, 1000 * Math.random() * 10)
      })
    }

    let finalData
    watch(obj, async (oldValue, newValue, onInvalidate) => {
      let expired = false
      onInvalidate(() => {
        expired = true
      })
      const data = await fetch(obj.foo)
      if (!expired) {
        finalData = data
        console.log(finalData, 'finalData')
      }
      console.log(data)
    }, {
      // immediate: true,
      flush: 'post'
    })

    obj.foo++
    setTimeout(() => {
      obj.foo++
    })

    


  </script>
</body>
</html>